package com.coai.gateway.filter

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import reactor.core.publisher.Mono

/**
 * 限流配置
 */
@Configuration
class RateLimitConfig {
    
    /**
     * 基于用户ID的限流
     */
    @Bean
    fun userKeyResolver(): KeyResolver {
        return KeyResolver { exchange ->
            val userId = exchange.request.headers.getFirst("X-User-Id")
            Mono.just(userId ?: exchange.request.remoteAddress?.address?.hostAddress ?: "anonymous")
        }
    }
    
    /**
     * 基于IP的限流
     */
    @Bean
    fun ipKeyResolver(): KeyResolver {
        return KeyResolver { exchange ->
            Mono.just(exchange.request.remoteAddress?.address?.hostAddress ?: "unknown")
        }
    }
}
